package com.demo.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;
import org.springframework.mail.SimpleMailMessage;
import jakarta.mail.MessagingException;

import jakarta.mail.internet.MimeMessage;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;




/**
 * 邮箱API
 */
@Slf4j
@Component
public class EmailApi {
    @Autowired
    private JavaMailSender mailSender;
    @Autowired
    private  TemplateEngine templateEngine;
    private String from="15072693267@163.com" ;// 发件人
    public void sendEmail(String to, String subject, String content) {
        // 创建邮件对象
        SimpleMailMessage message = new SimpleMailMessage();
        // 设置邮件发送人
        message.setFrom(from);
        // 设置邮件接收人
        message.setTo(to);
        // 设置邮件主题
        message.setSubject(subject);
        // 设置邮件内容
        message.setText(content);
        // 发送邮件
        mailSender.send(message);
    }

    /**
     * 发送验证码
     * @param to 收件人
     * @param subject 主题
     * @param code 代码
     * @param type 类型    register'：'注册'  'login'：'登录'     其他：'忘记密码'
     * @throws MessagingException
     */
    public void sendVerificationEmail(String to, String subject, String code, String type) throws MessagingException {
            // 准备Thymeleaf模板上下文
            Context context = new Context();
            context.setVariable("code", code);
            context.setVariable("type", type);
            context.setVariable("time", LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            // 处理模板生成HTML内容
            String htmlContent = templateEngine.process("email/verification-code", context);
            // 创建MIME消息
            MimeMessage message = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(htmlContent, true);
            // 发送邮件
            mailSender.send(message);
            log.info("邮件发送成功：{}", to);


    }

}
